package net.sahv.bdyz.api;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;

import net.sahv.bdyz.model.Address;
import net.sahv.bdyz.model.Fabric;
import net.sahv.bdyz.model.Member;
import net.sahv.bdyz.model.Pattern;
import net.sahv.bdyz.model.PatternPrint;
import net.sahv.bdyz.model.ShoppingCart;
import net.sahv.bdyz.service.AddressService;
import net.sahv.bdyz.service.FabricService;
import net.sahv.bdyz.service.MemberService;
import net.sahv.bdyz.service.OrdersListService;
import net.sahv.bdyz.service.OrdersService;
import net.sahv.bdyz.service.PatternPrintService;
import net.sahv.bdyz.service.PatternService;
import net.sahv.bdyz.service.ShoppingCartService;
import net.sahv.bdyz.util.Jiage;
import net.sahv.bdyz.util.LoadCfgUtil;
import net.sahv.bdyz.util.PageInfo;

@Controller
@RequestMapping("api/orders/")
public class OrdersApiController {
	@Autowired
	private MemberService memberService;
	@Autowired
	private OrdersService ordersService;
	@Autowired
	private OrdersListService orderListsService;
	@Autowired
	private PatternService patternService;
	@Autowired
	private FabricService fabricService;
	@Autowired
	private PatternPrintService patternPrintService;
	@Autowired
	private ShoppingCartService shoppingCartService;
	@Autowired
	private AddressService addressService;
	@Autowired 
	CookieLocaleResolver resolver;

	/**
	 * 点击直接购买查看购买属性
	 * 
	 * @author 薛国计
	 * @date 2016年8月6日
	 * @param request
	 * @param status
	 *            分类 0、印花；1、买断；2、成品；3、面料；
	 * @param pId
	 *            花型id
	 * @param ppId
	 *            印花工艺id
	 * @param fId
	 *            面料id
	 * @param size
	 *            数量
	 * @return
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	@RequestMapping(value = "viewinsertorders", method = RequestMethod.POST)
	public String viewinsertorders(HttpServletRequest request, Model model, String status, String pId, String ppId,
			String fId, String size,String colorImg) throws FileNotFoundException, IOException {
		Map<String, String> mapUrls = LoadCfgUtil.loadCfg();
		String imgParent = mapUrls.get("targetUrl.img");
		ordersService.huigun();
		Integer mId =  (Integer) request.getSession().getAttribute("mId");
		if(mId==null){
			return "api/toPhonePage/login";
		}
		List<Address> addressdefault = addressService.selectAllByMid(mId); //地址
		Address address = addressService.finddefault(mId);//默认地址
		model.addAttribute("addressdefault", addressdefault);
		model.addAttribute("address", address);
		
		
		model.addAttribute("size", size);
		model.addAttribute("status", status);
		model.addAttribute("pId", pId);
		model.addAttribute("ppId", ppId);
		model.addAttribute("fId", fId);
		if (status.equals("0")) {
			PatternPrint patternPrint = patternPrintService.selectByPrimaryKey(Integer.valueOf(ppId));// 印花工艺
			Pattern pattern = patternService.selectByPrimaryKey(Integer.valueOf(pId));// 花型
			pattern.setpImg(imgParent + pattern.getpImg());
			if (pattern.getpBuyoutState().equals(1)) {
				return "member/member/maiduan";
			}
			model.addAttribute("patternPrint", patternPrint);
			model.addAttribute("pattern", pattern);
			model.addAttribute("jiage", patternPrint.getPpPrice());
			Integer sizee = Integer.valueOf(size);
			BigDecimal heji = Jiage.yinhua(sizee);
				model.addAttribute("heji",patternPrint.getPpPrice().multiply(heji).setScale(2, BigDecimal.ROUND_HALF_UP));
		}
		if (status.equals("1")) {
			Pattern pattern = patternService.selectByPrimaryKey(Integer.valueOf(pId));// 花型
			pattern.setpImg(imgParent + pattern.getpImg());
			if (pattern.getpBuyoutState().equals(1)) {
				return "member/member/maiduan";
			}
			model.addAttribute("pattern", pattern);
			model.addAttribute("jiage", pattern.getpBuyoutPrice());
			model.addAttribute("heji",pattern.getpBuyoutPrice());
		}
		if (status.equals("2")) {
			PatternPrint patternPrint = patternPrintService.selectByPrimaryKey(Integer.valueOf(ppId));// 印花工艺
			Pattern pattern = patternService.selectByPrimaryKey(Integer.valueOf(pId));// 花型
			Fabric fabric = fabricService.selectByPrimaryKey(Integer.valueOf(fId)); // 面料
			pattern.setpImg(imgParent + pattern.getpImg());
			if (pattern.getpBuyoutState().equals(1)) {
				return "member/member/maiduan";
			}
			model.addAttribute("patternPrint", patternPrint);
			model.addAttribute("pattern", pattern);
			model.addAttribute("fabric", fabric);
			model.addAttribute("jiage",patternPrint.getPpPrice().add(fabric.getfPrice()));
			Integer sizee = Integer.valueOf(size);
			model.addAttribute("heji",patternPrint.getPpPrice().multiply(Jiage.yinhua(sizee)).add(fabric.getfPrice().multiply(Jiage.mianliao(sizee))).setScale(2, BigDecimal.ROUND_HALF_UP));
		}
		if (status.equals("3")) {
			Fabric fabric = fabricService.selectByPrimaryKey(Integer.valueOf(fId)); // 面料
			model.addAttribute("fabric", fabric);
			model.addAttribute("jiage", fabric.getfPrice());
			Integer sizee = Integer.valueOf(size);
			BigDecimal heji = Jiage.mianliao(sizee);
				model.addAttribute("heji",fabric.getfPrice().multiply(heji).setScale(2, BigDecimal.ROUND_HALF_UP));
				model.addAttribute("colorImg", colorImg);
		}
		return "phone/fitting/justbuy";

	}

	

	

	/**
	 * 从购物车去结算
	 * 
	 * @author 薛国计
	 * @date 2016年8月6日
	 * @param request
	 * @param oId
	 * @return
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	@RequestMapping(value = "caraccount", method = RequestMethod.POST)
	public String caraccount(HttpServletRequest request, String[] oId, Model model, HttpServletResponse response)
			throws FileNotFoundException, IOException {
		Map<String, String> mapUrls = LoadCfgUtil.loadCfg();
		String imgParent = mapUrls.get("targetUrl.img");
		ordersService.huigun();
		Object languageObj=request.getSession().getAttribute("language");
		 String yuyan="";
		if(languageObj!=null){
			String language=String.valueOf(languageObj);
			if(language!=null&&!language.equals("")){
				language=language.toLowerCase();
				if(language.equals("zh_cn")){
					yuyan="ch";
					resolver.setLocale(request, response, Locale.CHINA );
				}else if(language.equals("en")){
					yuyan="en";
					resolver.setLocale(request, response, Locale.ENGLISH );
				}else{
					yuyan="ch";
					resolver.setLocale(request, response, Locale.CHINA );
				}
			}
		}else{
			yuyan="ch";
		}
		Member member = memberService.getCurrent();//获取当前登录人信息
		List<Address> addressdefault = addressService.selectAllByMid(member.getmId()); //地址
		Address address = addressService.finddefault(member.getmId());//默认地址
		
		List<ShoppingCart> list = new ArrayList<>();
		for (String item : oId) {
			ShoppingCart shoppingCart = shoppingCartService.selectByPrimaryKey(Integer.valueOf(item));
			if(shoppingCart.getScType().equals(0)||shoppingCart.getScType().equals(2)){
				if(yuyan.equals("ch")){//借用下购物车id
					shoppingCart.setScNo(patternPrintService.selectByPrimaryKey(shoppingCart.getPpId()).getPpName());
				}
				if(yuyan.equals("en")){
					shoppingCart.setScNo(patternPrintService.selectByPrimaryKey(shoppingCart.getPpId()).getPpNameEn());
				}
			}
			shoppingCart.setScPatternImg(imgParent + shoppingCart.getScPatternImg());
			list.add(shoppingCart);
		}
		model.addAttribute("list", list);
		model.addAttribute("addressdefault", addressdefault);
		model.addAttribute("address", address);
		model.addAttribute("oId", oId);
		return "phone/userCenter/justbuy";

	}
	
	
	/**
	 * 查看我的订单
	 * 
	 * @author 薛国计
	 * @date 2016年8月8日
	 * @param request
	 * @param pageInfo
	 * @return
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 */
	@RequestMapping(value = "orderslist", method = RequestMethod.GET)
	public String orderslist(HttpServletRequest request, PageInfo pageInfo, Model model,HttpServletResponse response) throws FileNotFoundException, IOException {
		Map<String,String> mapUrls=LoadCfgUtil.loadCfg();
		String imgParent=mapUrls.get("targetUrl.img");
		Object languageObj=request.getSession().getAttribute("language");
		 String yuyan="";
		if(languageObj!=null){
			String language=String.valueOf(languageObj);
			if(language!=null&&!language.equals("")){
				language=language.toLowerCase();
				if(language.equals("zh_cn")){
					yuyan="ch";
					resolver.setLocale(request, response, Locale.CHINA );
				}else if(language.equals("en")){
					yuyan="en";
					resolver.setLocale(request, response, Locale.ENGLISH );
				}else{
					yuyan="ch";
					resolver.setLocale(request, response, Locale.CHINA );
				}
			}
		}else{
			yuyan="ch";
		}
		
		ordersService.huigun();
		List<Map<String, Object>> listorder = new ArrayList<>();
		Member member = memberService.getCurrent();//获取当前登录人信息
		
		if(member==null){
		
			return "web/main/index";
		}
		String where = " 1=1 AND O_STATE!=3 and M_ID="+ member.getmId();
		List<Map<String, Object>> list = ordersService.findAll(pageInfo, where, " ORDER BY O_ID DESC ");
		for (Map<String, Object> item : list) {
			Map<String, Object> map = new HashMap<>();
			List<Map<String, Object>> orderlist = orderListsService
					.selectAllByOrdersId(Integer.valueOf(item.get("O_ID").toString()),yuyan);
			for(Map<String, Object> orderlistOne:orderlist){
				String OL_PATTERN_IMG=(String) orderlistOne.get("OL_PATTERN_IMG");
				orderlistOne.remove("OL_PATTERN_IMG");
				orderlistOne.put("OL_PATTERN_IMG", imgParent+OL_PATTERN_IMG);
			}
			
			map.put("orders", item);
			map.put("orderlist", orderlist);
			listorder.add(map);

		}
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("listorder", listorder);
		return "phone/userCenter/myOrder";

	}

	

	/**
	 * 订单详情
	 * 
	 * @author 薛国计
	 * @date 2016年8月8日
	 * @param request
	 * @param oId
	 *            订单id
	 * @return
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 */
	@RequestMapping(value = "orderDetailToPaid{oId}", method = RequestMethod.GET)
	public String vieworders(@PathVariable("oId")String oId,HttpServletRequest request, Model model,HttpServletResponse response) throws FileNotFoundException, IOException {
		
Map<String, String> mapUrls = LoadCfgUtil.loadCfg();
		
		model.addAttribute("imgpath",mapUrls.get("targetUrl.img"));
		
		Object languageObj=request.getSession().getAttribute("language");
		 String yuyan="";
		if(languageObj!=null){
			String language=String.valueOf(languageObj);
			if(language!=null&&!language.equals("")){
				language=language.toLowerCase();
				if(language.equals("zh_cn")){
					yuyan="ch";
					resolver.setLocale(request, response, Locale.CHINA );
				}else if(language.equals("en")){
					yuyan="en";
					resolver.setLocale(request, response, Locale.ENGLISH );
				}else{
					yuyan="ch";
					resolver.setLocale(request, response, Locale.CHINA );
				}
			}
		}else{
			yuyan="ch";
		}
		ordersService.huigun();
		model.addAttribute("orders", ordersService.selectByPrimaryKey(Integer.valueOf(oId)));
		model.addAttribute("orderslist", orderListsService.selectAllByOrdersId(Integer.valueOf(oId),yuyan));
		return "phone/userCenter/orderDetail";
	}
	
	@RequestMapping(value = "pay", method = RequestMethod.POST)
	public String pay(String oId,HttpServletRequest request,HttpServletResponse response, Model model) {
		synchronized (this) {
			String sHtmlText;
			try {
				sHtmlText = ordersService.pay(oId);
			} catch (Exception e) {
				e.printStackTrace();
				return "member/member/maiduan";
			}
			
		model.addAttribute("pay", sHtmlText);
		  return "member/member/alipayapi";
		
	}
	
	}
	
	@RequestMapping(value = "vip", method = RequestMethod.GET)
	public String vip(HttpServletRequest request,Model model) {
		Member member = memberService.getCurrent();//获取当前登录人信息
		model.addAttribute("pay",ordersService.vip(member.getmId()));
		 return "member/member/alipayapi";
	}
	

}
